
local ngx = _G.ngx

local METHOD = ngx.req.get_method()

if METHOD == "POST" then
  local httparg    = require("shared.api.httparg")
  local response   = require("shared.api.response")
  local config     = require("config")
  local tag        = httparg.tag()
  local cjson      = require "cjson.safe"


  local ARGS = {
    username  = tag.form.username  ('string', 'required'),
    currency  = tag.form.currency  ('string', 'required'),
    amount    = tag.form.amount    ('string', 'required'),
  }

  -- response.success(ARGS)

  local httpclient  = require "shared.http.client"
  local proxyhelper = require "shared.api.proxy-helper"
  local def         = require "shared.api.def"

  -- retreive account
  local ACCOUNT
  do
    local ADDRESS = config.ENV.DATAGATE_SERVICE

    local location = ngx.unescape_uri(ADDRESS..'/account')
    local method   = 'PEEK'
    local data = cjson.encode({
      username = ARGS.username,
    })

    -- perform http request
    local resp, err = httpclient.new()
      :uri(location)
      :body(data)
      :send(method, 2000, nil)

    if err or (not resp) then
      ngx.status = 500
      ngx.say(err)
      ngx.exit(ngx.OK)
    end

    -- has body? has headers? is status 200 OK? is application/json?
    if   not resp.body
      or not resp.headers
      or resp.status ~= 200
      or not proxyhelper.is_match_content_type(resp, 'application/json')  then

      ngx.status = resp.status
      -- fill header except 'Server'
      proxyhelper.fill_response_header(resp.headers)
      ngx.say(resp.body)
      ngx.exit(ngx.OK)
    end

    local body
    -- according 'Content-Encoding' to decode response body
    local contentDecoder = proxyhelper.get_content_decoder(resp)
    if contentDecoder then
      body = contentDecoder.decode(resp.body)
    else
      response.failure(def.ERROR_CODE.UNKNOWN_FAILTURE, 'UNKNOWN_ENCODING')
    end

    if type(body)=="table" then
      ACCOUNT = body.account
    end
  end

  -- commit transaction
  do
    local ADDRESS = config.ENV.WALLET_SERVICE

    local location = ngx.unescape_uri(ADDRESS..'/transaction')
    local method   = 'COMMIT'
    local data = cjson.encode({
      account                = ACCOUNT,
      player                 = ARGS.username,
      alliance               = "muse",
      type                   = "transfer",
      wallet                 = ARGS.currency,
      amount                 = ARGS.amount,
      operation_idempotence  = ARGS.username.."-"..ARGS.currency.."-"..tostring(ngx.time()),
    })

    -- perform http request
    local resp, err = httpclient.new()
      :uri(location)
      :body(data)
      :send(method, 2000, nil)

    if err or (not resp) then
      ngx.status = 500
      ngx.say(err)
      ngx.exit(ngx.OK)
    end

    -- has body? has headers? is status 200 OK? is application/json?
    if   not resp.body
      or not resp.headers
      or resp.status ~= 200
      or not proxyhelper.is_match_content_type(resp, 'application/json')  then

      ngx.status = resp.status
      -- fill header except 'Server'
      proxyhelper.fill_response_header(resp.headers)
      ngx.say(resp.body)
      ngx.exit(ngx.OK)
    end

    local body
    -- according 'Content-Encoding' to decode response body
    local contentDecoder = proxyhelper.get_content_decoder(resp)
    if contentDecoder then
      body = contentDecoder.decode(resp.body)
    else
      response.failure(def.ERROR_CODE.UNKNOWN_FAILTURE, 'UNKNOWN_ENCODING')
    end

    response.success(body)
  end
end



if METHOD == "GET" then
  ngx.header.content_type = "text/html; charset=utf8"
  ngx.say([[
  <html>
    <header>
      <title>OCP 新增錢包</title>
    </header>
    <body>
      <div>
        <form method="post">
          <fieldset>
            <legend>虛擬存款到帳戶錢包</legend>
            <p>
              <label for="username">帳戶名稱</label>
              <input type="text" name="username" id="username" value="" autocomplete="off">
            </p>
            <p>
              <label for="currency">存款幣別</label>
              <input type="text" name="currency" id="currency" value="" autocomplete="off">
            </p>
            <p>
              <label for="amount">存款金額</label>
              <input type="text" name="amount" id="amount" value="" autocomplete="off">
            </p>
          </fieldset>
          <input type="reset" value="清除">
          <input type="submit" value="送出">
        </form>
      </div>
    </body>
  </html>
  ]])
end

